package com.unitd.frame.sso.web.filter;

import com.unitd.frame.comm.utils.BooleanUtils;
import com.unitd.frame.comm.utils.http.HttpUtils;
import com.unitd.frame.sso.web.waf.request.WafRequestWrapper;
import com.unitd.frame.comm.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * @desc Waf防火墙过滤器, 用于防止脚本攻击,sql注入过滤
 * @filename WafFilter.java
 * @copyright www.unitd.com
 * @author Hudan
 * @version 1.0
 * @date 2016/10/18
 */
public class WafFilter implements Filter {

	private static final Logger logger = LoggerFactory.getLogger(WafFilter.class.getName());

	private static String OVER_URL = null; 									// 非过滤地址
	private static boolean FILTER_XSS = true; 								// 开启XSS脚本过滤
	private static boolean FILTER_SQL = true; 								// 开启SQL注入过滤


	@Override
	public void init(FilterConfig config) {
		// 读取Web.xml配置地址
		OVER_URL = config.getInitParameter("over.url");
		FILTER_XSS = getParamConfig(config.getInitParameter("filter_xss"));
		FILTER_SQL = getParamConfig(config.getInitParameter("filter_sql_injection"));
	}


	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
			ServletException {
		HttpServletRequest req = (HttpServletRequest) request;

		boolean isOver = HttpUtils.inContainURL(req, OVER_URL);

		// 非拦截URL、直接通过
		if (!isOver) {
			try {
				// Request请求XSS过滤
				chain.doFilter(new WafRequestWrapper(req, FILTER_XSS, FILTER_SQL), response);
			} catch (Exception e) {
				logger.error("XSS过滤出现异常["+ e.getMessage() +"],equestURL: " + req.getRequestURL());
			}
			return;
		}
		chain.doFilter(request, response);
	}


	@Override
	public void destroy() {
		logger.debug(" WafFilter destroy .");
	}

	/**
	 * @desc 获取参数配置
	 * @param value 配置参数
	 * @return 未配置返回 True
	 */
	private boolean getParamConfig(String value) {
		if(StringUtils.isBlank(value)) {
			//未配置默认 True
			return true;
		}
		return BooleanUtils.toBoolean(value);
	}
}